package com.htht.smartschool.service.login;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.htht.smartschool.common.service.BaseService;
import com.htht.smartschool.dao.user.UserDao;
import com.htht.smartschool.model.user.TUser;
import com.htht.smartschool.util.system.EncryptUtil;

public class LoginService extends BaseService{
	UserDao userDao = new UserDao();
	/**
	 * 用户登录
	 * @param tuser
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map login(TUser tuser) {
		String epass = EncryptUtil.encryptMd5Password2(tuser.getPassword());
		String ekey = EncryptUtil.encryptMd5Password2(tuser.getUsercode()+tuser.getUsertype());
		String hql = String.format("from TUser where userkey='%1$s' and password='%2$s' and usertype=%3$s", ekey, epass, tuser.getUsertype());
		
		TUser user = (TUser) getDao().queryFirstByHQL(hql);
		Map map = new HashMap();
		if (user == null) {
			return null;
		}else if(user.getIslock() == false){
			map.put("info", "用户已锁定，请与管理员联系解锁！");
			return map;
		}else{
			user = shieldUserInfo(user);//处理返回字段
			//关于Redis
//			RedisUtil.getInstance().setString(RedisKeyConstant.STARTLINEDATE, String.valueOf(new Date().getTime()));
//			RedisUtil.getInstance().setString(RedisKeyConstant.LASTONLINEDATE, String.valueOf(new Date().getTime()));
//			UserOnlineUtil.online(user);
			String sqlru = "select * from t_role_user where userkey = '"+user.getUserkey()+"'";
			List<Object[]> list = getDao().queryBySQL(sqlru);
			StringBuffer su = new StringBuffer();
			for (Object[] obj: list) {
				su.append(String.valueOf(obj[1])+",");
			}
			String rolecodes = su.toString();
			if(rolecodes.length() > 0){
				user.setRolecodes(rolecodes.substring(0,rolecodes.length()-1));
			}
			user.setMessageid(String.valueOf(user.getId()));
			user.setRemark(String.valueOf(user.getRemark()));
			user.setSchoolcode(String.valueOf(user.getSchoolcode()));
			map.put("userinfo", user);
			return map;
		} 
	}
	public TUser shieldUserInfo(TUser user){
		user.setPassword(null);
		user.setIslock(null);
		user.setRegion(null);
		user.setUsertype(null);
		user.setModel(null);
		user.setAndroid(null);
		user.setImei(null);
		user.setRegtype(null);
		user.setVcode(null);
		return user;
	}
	public TUser checkUser(TUser tuser){
		int userType = tuser.getUsertype();
		String userCode = tuser.getUsercode();
		String userKey = tuser.getUserkey();
		String hql = String.format("from TUser where usercode = '%1$s' AND usertype = '%2$S' AND userkey = '%3$s'", userCode , userType , userKey);
		TUser user = (TUser) getDao().queryFirstByHQL(hql);
		return user;
	}
}
